/* eslint-disable */
import { message } from 'antd'

export const getHash = (hash) => {
  const arr = hash.split('/')
  return arr[arr.length - 1]
}

//更改icon
export const changeFavicon = link => {
  let $favicon = document.querySelector('link[rel="shortcut icon"]')
  if ($favicon !== null) {
    $favicon.href = link
  } else {
    $favicon = document.createElement('link')
    $favicon.rel = 'icon'
    $favicon.href = link
    document.head.appendChild($favicon)
  }
}

//修改title
export const changeTitle = title => {
  document.title = title
}

export const getBrowserInfo = () => {
  const agent = navigator.userAgent.toLowerCase()
  const arr = []
  const system = agent.split(' ')[1].split(' ')[0].split('(')[1]
  arr.push(system)
  const REGSTR_EDGE = /edge\/[\d.]+/gi
  const REGSTR_IE = /trident\/[\d.]+/gi
  const OLD_IE = /msie\s[\d.]+/gi
  const REGSTR_FF = /firefox\/[\d.]+/gi
  const REGSTR_CHROME = /chrome\/[\d.]+/gi
  const REGSTR_SAF = /safari\/[\d.]+/gi
  const REGSTR_OPERA = /opr\/[\d.]+/gi
  // IE
  if (agent.indexOf('trident') > 0) {
    arr.push(agent.match(REGSTR_IE)[0].split('/')[0])
    arr.push(agent.match(REGSTR_IE)[0].split('/')[1])
    return arr
  }
  // OLD_IE
  if (agent.indexOf('msie') > 0) {
    arr.push(agent.match(OLD_IE)[0].split(' ')[0])
    arr.push(agent.match(OLD_IE)[0].split(' ')[1])
    return arr
  }
  // Edge
  if (agent.indexOf('edge') > 0) {
    arr.push(agent.match(REGSTR_EDGE)[0].split('/')[0])
    arr.push(agent.match(REGSTR_EDGE)[0].split('/')[1])
    return arr
  }
  // firefox
  if (agent.indexOf('firefox') > 0) {
    arr.push(agent.match(REGSTR_FF)[0].split('/')[0])
    arr.push(agent.match(REGSTR_FF)[0].split('/')[1])
    return arr
  }
  // Opera
  if (agent.indexOf('opr') > 0) {
    arr.push(agent.match(REGSTR_OPERA)[0].split('/')[0])
    arr.push(agent.match(REGSTR_OPERA)[0].split('/')[1])
    return arr
  }
  // Safari
  if (agent.indexOf('safari') > 0 && agent.indexOf('chrome') < 0) {
    arr.push(agent.match(REGSTR_SAF)[0].split('/')[0])
    arr.push(agent.match(REGSTR_SAF)[0].split('/')[1])
    return arr
  }
  // Chrome
  if (agent.indexOf('chrome') > 0) {
    arr.push(agent.match(REGSTR_CHROME)[0].split('/')[0])
    arr.push(agent.match(REGSTR_CHROME)[0].split('/')[1])
    return arr
  }
  arr.push('未获取到浏览器信息')
  return arr
}

export const getWeek = () => {
  const arr = []
  const week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
  for (let i = 0; i < 7; i++) {
    arr.push({
      name: week[i],
      id: i + 1
    })
  }
  return arr
}

export const getmonth = () => {
  const y = new Date().getFullYear()
  const m = new Date().getMonth()

  // eslint-disable-next-line no-shadow
  function getDaysInOneMonth(y, m) {
    const d = new Date(y, m + 1, 0)
    return d.getDate()
  }

  const arr = []
  for (let i = 1; i < 31 + 1; i++) {
    arr.push({
      name: `${i}号`,
      id: i
    })
  }
  return arr
}

export const gethours = () => {
  const arr = []
  for (let i = 1; i < 24; i++) {
    arr.push({
      name: `${i}小时`,
      id: i
    })
  }
  return arr
}

export const getminute = () => {
  const arr = [
    {
      id: 2,
      name: `${2}分钟`
    }
  ]
  for (let i = 5; i <= 55; i += 5) {
    arr.push({
      name: `${i}分钟`,
      id: i
    })
  }
  return arr
}

export const listToTree = (data, options) => {
  options = options || {}
  const ID_KEY = options.idKey || 'id'
  const PARENT_KEY = options.parentKey || 'parent'
  const CHILDREN_KEY = options.childrenKey || 'children'

  const tree = []
  const childrenOf = {}
  let item
  let id
  let parentId

  for (let i = 0, length = data.length; i < length; i++) {
    item = data[i]
    id = item[ID_KEY]
    parentId = item[PARENT_KEY] || 0
    // every item may have children
    childrenOf[id] = childrenOf[id] || []
    // init its children
    item[CHILDREN_KEY] = childrenOf[id]
    if (parentId != 0) {
      // init its parent's children object
      childrenOf[parentId] = childrenOf[parentId] || []
      // push it into its parent's children object
      childrenOf[parentId].push(item)
    } else {
      tree.push(item)
    }
  }

  return tree
}

/**
 * 中文算两个字符 计算字符串的长度
 * @param {String} val
 * @returns {Number} byteValLen 字符长度
 */
export const getStrByteLen = (val = '') => {
  let byteValLen = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/gi) != null) byteValLen += 2
    else byteValLen += 1
  }
  return byteValLen
}

export function getParameterByName(name, url) {
  if (!url) url = window.location.href
  name = name.replace(/[\[\]]/g, '\\$&')
  const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`)
  const results = regex.exec(url)
  if (!results) return null
  if (!results[2]) return ''
  return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

/**
 * 获取hash的query字段，如果没有则返回null
 * @param {String} name 查询字段名
 */
export function getHashParameterByName(name) {
  const hash = window.location.hash || ''
  if (!hash) return null
  let result = getParameterByName(name, hash.replace(/%/g, '%25'))
  if (result) {
    // 中文解码
    result = decodeURIComponent(result)
  }
  return result
}

export const firstLetterUpper = (a) => a.slice(0, 1).toUpperCase() + a.slice(1)
export const getUrl = (data) => {
  let arr = []
  let bool = true
  if (window.location.hash.indexOf('?') != -1) {
    const val = window.location.hash.split('?')[0]
    val.indexOf('/') != -1 ? (arr = val.split('/')) : null
  } else {
    const val = window.location.hash
    val.indexOf('/') != -1 ? (arr = val.split('/')) : null
  }
  arr.splice(0, 1)
  data &&
    data.map((obj) => {
      arr &&
        arr.length &&
        arr.map((url, key) => {
          if (obj.url.indexOf(url) != -1 && key < 1) {
            bool = false
          }
        })
    })
  return bool
}

export const HBaseTarget = (name) => {
  let target = ''
  if (name) {
    const arr = name.split(':')
    const str = arr.join('_')
    target = str
  }
  return target
}

// 判断是否在使用oss
export const formilyEditorPath =
  window.rootPath === 'https://xuelangyun-hufu.oss-cn-hangzhou.aliyuncs.com'
    ? 'index-oss.html'
    : 'index.html'

/**
 * 获取当前登录用户信息
 */
export const getUserInfo = () => JSON.parse(sessionStorage.getItem('userList')) || {}

/*
 * 构造jdbc连接字符串
 * 参考资料 https://baijiahao.baidu.com/s?id=1597248754463701753&wfr=spider&for=pc
 */
export const buildJDBCLink = (type, props) => {
  let defaultProps = {
    server: "",
    port: "",
    dbName: "",
    connectionProperty: ""
  };
  let {
    server,
    port,
    dbName,
    connectionProperty
  } = _.defaults(props, defaultProps);
  /**
   * old
   *     case "MySQL":
   *       return `jdbc:mysql://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""   }`;
   *     case "TiDB":
   *       return `jdbc:mysql://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""   }`;
   *     case "KINGBASE8":
   *       return `jdbc:kingbase8://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""    }`;
   *     case "DM":
   *       return `jdbc:dm://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""         }`;
   *     case "SQLServer":
   *       return `jdbc:sqlserver://${server}:${port};DataBaseName=${dbName}`;
   *     case "PostgreSQL":
   *       return `jdbc:postgresql://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""       }`;
   *     case "DB2":
   *       return `jdbc:db2://${server}:${port}/${dbName}`;
   *     case "Oracle":
   *       return `jdbc:oracle:thin:@${server}:${port}:${dbName}`;
   *     case "Oracle:ServiceName":
   *       return `jdbc:oracle:thin:@//${server}:${port}/${dbName}`;
   *     case "Sap":
   *       return `jdbc:sap://${server}:${port}${connectionProperty ? "?" + connectionProperty : ""       }`;
   *     case "Hive":
   *       return `jdbc:hive2://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""    }`;
   *     case "Mongodb":
   *       return `${server}:${port}`;
   *     case "HDFS":
   *       return `hdfs://${server}:${port}`;
   *     case "MatrixDB":
   *       return `jdbc:postgresql://${server}:${port}/${dbName}${connectionProperty ? "?" + connectionProperty : ""     }`;
   *   }
   */
  //通用提取1：ip
  const ip = `${server}:${port}`

  switch (type) {
    // 独立处理 SQLServer Mongodb HDFS，如果详解归纳增加功能解释的复杂度
    case "SQLServer":
      return `jdbc:sqlserver://${ip};DataBaseName=${dbName}`;
    case "Mongodb":
      return ip;
    case "HDFS":
      return `hdfs://${ip}`;
    case "AS400":
      return `jdbc:as400://${server};libraries=${dbName};`;
    case "Oracle":
      const _type = String(type).toLowerCase()
      // 转小写字母
      const _typeSelect = `.${_type}.`
      // 声明 _typeSelect 为对照字符串
      const _typeSelectObj = '.mysql.tidb.kingbase8.dm.db2.oracle.oracle:servicename.postgresql.sap.hive.matrixdb.'
      // 用includes过滤对照字符串，如果不包含则返回''
      if (!_typeSelectObj.includes(_typeSelect)) return ''
      // 根据对照字符串 进行dbName后面跟随内容的特殊处理
      const _dbNameSelectObj = '.mysql.tidb.kingbase8.dm.postgresql.sap.hive.'
      const _dbNameNext = _dbNameSelectObj.includes(_typeSelect) ? (connectionProperty ? "?" + connectionProperty : "") : ''
      // 根据对照字符串和小写 type处理type前缀的内容
      const _typeNextSelectObj = { 'oracle': 'oracle:thin:@', 'oracle:servicename': 'oracle:thin:@//' }
      const _typeNext__ = _typeNextSelectObj[_type] || (_type === 'tidb' ? 'mysql' : _type === 'hive' ? 'hive2' : _type === 'matrixdb' ? 'postgresql' : _type) + '://'
      return `jdbc:${_typeNext__}${ip}:${dbName}${_dbNameNext}`
    default: {
      const _type = String(type).toLowerCase()
      // 转小写字母
      const _typeSelect = `.${_type}.`
      // 声明 _typeSelect 为对照字符串
      const _typeSelectObj = '.mysql.tidb.kingbase8.dm.db2.oracle.oracle:servicename.postgresql.sap.hive.matrixdb.'
      // 用includes过滤对照字符串，如果不包含则返回''
      if (!_typeSelectObj.includes(_typeSelect)) return ''
      // 根据对照字符串 进行dbName后面跟随内容的特殊处理
      const _dbNameSelectObj = '.mysql.tidb.kingbase8.dm.postgresql.sap.hive.'
      const _dbNameNext = _dbNameSelectObj.includes(_typeSelect) ? (connectionProperty ? "?" + connectionProperty : "") : ''
      // 根据对照字符串和小写 type处理type前缀的内容
      const _typeNextSelectObj = { 'oracle': 'oracle:thin:@', 'oracle:servicename': 'oracle:thin:@//' }
      const _typeNext__ = _typeNextSelectObj[_type] || (_type === 'tidb' ? 'mysql' : _type === 'hive' ? 'hive2' : _type === 'matrixdb' ? 'postgresql' : _type) + '://'
      return `jdbc:${_typeNext__}${ip}/${dbName}${_dbNameNext}`
    }
  }
};
